package com.anche.cywebnew.Service.systemManager.Impl;

import com.anche.cywebnew.DAO.systemManager.TerminalMapper;
import com.anche.cywebnew.DAO.systemManager.UserMapper;
import com.anche.cywebnew.DTO.ModuleTreeDTO;
import com.anche.cywebnew.Pojo.systemManager.SysUser;
import com.anche.cywebnew.Pojo.systemManager.TerminalInfo;
import com.anche.cywebnew.Service.securityManager.SecurityLogService;
import com.anche.cywebnew.Service.systemManager.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private SecurityLogService securityLogService;

    @Override
    public SysUser findUserByLoginName(String loginname) {
        return userMapper.getUserByLoginName(loginname);
    }

    @Override
    public TerminalInfo findTerminalByIp(HttpServletRequest request) {
        String ip = getIpAddr(request);
        TerminalInfo terminalInfo = terminalMapper.getTerminalByIP(ip);
        if (terminalInfo == null) {
            terminalInfo = new TerminalInfo();
            terminalInfo.setTerminal_id(ip);
            return terminalInfo;
        }
        return terminalInfo;
    }

    @Override
    public void userSucessLogin(HttpServletRequest request, String loginName) {
        String ip = getIpAddr(request);
        Date dateNow = new Date();
        userMapper.userSucessLogin(loginName, ip, dateNow);
    }

    @Override
    public List<ModuleTreeDTO> getUserPerms(String id) {
        return this.userMapper.getUserPerms(id);
    }

    @Override
    public void addUser(SysUser sysUser) {
        sysUser.setErrortimes(0); //初始登陆失败次数为0
        sysUser.setCreatedate(new Date());
        sysUser.setPassword(DigestUtils.md5Hex("888888"));  //初始密码为888888
        String jyw = DigestUtils.md5Hex(sysUser.getLoginname() + sysUser.getName() + sysUser.getSfzhm() + sysUser.getStatus());   //校验位加密方式为：loginName+name+sfzmhm+status的md5
        sysUser.setJyw(jyw);
        sysUser.setGxrq(new Date());
        userMapper.insertSysUser(sysUser);
    }

    @Override
    public Page<SysUser> getUserPager(Integer page, Integer limit, SysUser sysUser) {
        Page<SysUser> page1 = PageHelper.startPage(page, limit);
        List<SysUser> sysUsers = userMapper.getSysUsers(sysUser);
        for (SysUser user :  sysUsers) {
            String jyw = DigestUtils.md5Hex(user.getLoginname() + user.getName() + user.getSfzhm() + user.getStatus());   //校验位加密方式为：loginName+name+sfzmhm+status的md5
            if (!jyw.equals(user.getJyw())){
                user.setIsupdate(1);   // 数据篡改了
                securityLogService.insertSecurityLog("数据篡改", "查询用户【" + user.getLoginname() + "】信息时发现数据被篡改", user);
            }
            user.setJyw(null);    // 防止校验位数据被前端获取
        }
        return page1;
    }

    @Override
    public void setUser(SysUser sysUser) {
        sysUser.setGxrq(new Date());
        String jyw = DigestUtils.md5Hex(sysUser.getLoginname() + sysUser.getName() + sysUser.getSfzhm() + sysUser.getStatus());   //校验位加密方式为：loginName+name+sfzmhm+status的md5
        sysUser.setJyw(jyw);
        userMapper.updateUserById(sysUser);
    }

    @Override
    public void delUser(String id) {
        userMapper.deleteById(id);
    }

    @Override
    public List<Map<String, String>> getQuickAccess(String id) {
        List<Map<String, String>> permissionDTOS = userMapper.getUserPermsUseMap(id);
        return permissionDTOS;
    }

    /**
     * 获取登录用户IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}
